package com.maple.excel.utils;

import com.alibaba.excel.EasyExcel;
import org.springframework.util.Assert;

import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

/**
 * <p>excel工具类</p>
 *
 * @author maple
 */
public class EasyExcelUtils {

    /**
     * 导出excel
     */
    public static <T> void export(@NotNull HttpServletResponse response, @NotNull Class<T> clazz,
                                  @NotEmpty List<T> list, @NotNull String filename,
                                  @NotNull String sheetName) throws IOException {
        Assert.notNull(response, "response is required");
        Assert.notNull(clazz, "clazz is required");
        Assert.notEmpty(list, "list cannot be empty");
        Assert.notNull(filename, "filename is required");
        Assert.notNull(sheetName, "sheetName is required");
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        // 如果是中文需要做处理
        String fileName = URLEncoder.encode(filename, "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), clazz)
                .sheet(sheetName).doWrite(list);
    }

}
